package com.dai.zhenfujin.utils;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.dai.zhenfujin.view.RatioImageView;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.ByteArrayOutputStream;

import static com.hyphenate.util.EasyUtils.TAG;


/**
 * Author by huang
 * Date 2018/8/16.
 * for
 * @author Administrator
 */
public class ImageUtil {
    public static final String TAG2 = "ImageUtil";

    public static void setImage(ImageView imageView, String url) {
        Glide.with(imageView.getContext()).load(url)
                .into(imageView);
    }


    public static void imageLoad(Context context, final RatioImageView imageView, final String url) {
       /* Glide.with(imageView.getContext())
                .load(url)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY){
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }

                        int width = resource.getIntrinsicWidth();
                        int height = resource.getIntrinsicHeight();

                        Log.d(TAG2, "width = " + width + " height = " + height);
                        float ratio = (float) width / height;

                        Log.d(TAG2, "ratio = " + ratio);

                        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                        layoutParams.width = UIUtils.getScreenWidth(imageView.getContext())/3;
                        layoutParams.height = (int) Math.floor((UIUtils.getScreenWidth(imageView.getContext())/3) / ratio + 0.5);
                        imageView.setLayoutParams(layoutParams);

                        Log.d(TAG2, "viewWidth = " + imageView.getLayoutParams().width
                                + " viewHeight = " + imageView.getLayoutParams().height
                                + " viewRatio = " + (float) imageView.getLayoutParams().width / imageView.getLayoutParams().height);
                        return false;
                    }
                })
                .into(imageView);*/

        ImageLoaderUtil.displayImage(context, imageView, url, ImageLoaderUtil.getPhotoImageOption(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
                int w = bitmap.getWidth();
                int h = bitmap.getHeight();

                int newW;
                int newH;
                /*if (h > w * MAX_W_H_RATIO) {//h:w = 5:3
                    newW = parentWidth / 2;
                    newH = newW * 5 / 3;
                } else if (h < w) {//h:w = 2:3
                    newW = parentWidth * 2 / 3;
                    newH = newW * 2 / 3;
                } else {//newH:h = newW :w
                    newW = parentWidth / 2;
                    newW = h * newW / w;
                }*/

                float ratio = (float) w / h;

                Log.d(TAG2, "ratio = " + ratio);

                // ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                newW = UIUtils.getScreenWidth(imageView.getContext()) / 3;
                newH = (int) Math.floor((UIUtils.getScreenWidth(imageView.getContext()) / 3) / ratio + 0.5);
                // imageView.setLayoutParams(layoutParams);

                //   imageView.setLayoutParams(new ViewGroup.LayoutParams(newW, newH));
                //   imageView.layout(0, 0, newW, newH);

                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                params.width = newW;
                params.height = newH;
                imageView.setRatio(ratio);
                imageView.setLayoutParams(params);
                // ImageLoaderUtil.getImageLoader(context).displayImage(url, imageView, ImageLoaderUtil.getPhotoImageOption());

                Glide.with(context).load(url).apply(RequestOptions.bitmapTransform(new RoundedCorners(10)).centerInside())
                        .into(imageView);

                //  Glide.with(context).load(url)
                //  .into(imageView);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
    }


    /**
     * 图片的缩放方法
     *
     * @param bitmap  ：源图片资源
     * @param maxSize ：图片允许最大空间  单位:KB
     * @return
     */
    public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        // 单位：从 Byte 换算成 KB
        double currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩
        while (currentSize > maxSize) {
            // 计算bitmap的大小是maxSize的多少倍
            double multiple = currentSize / maxSize;
            // 开始压缩：将宽带和高度压缩掉对应的平方根倍
            // 1.保持新的宽度和高度，与bitmap原来的宽高比率一致
            // 2.压缩后达到了最大大小对应的新bitmap，显示效果最好
            bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple));
            currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        }
        return bitmap;
    }


    /**
     * bitmap转换成byte数组
     *
     * @param bitmap
     * @param needRecycle
     * @return
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            com.tencent.mm.opensdk.utils.Log.e(TAG, e.toString());
        }
        return result;
    }

    /**
     * 图片的缩放方法
     *
     * @param orgBitmap ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) {
        if (null == orgBitmap) {
            return null;
        }
        if (orgBitmap.isRecycled()) {
            return null;
        }
        if (newWidth <= 0 || newHeight <= 0) {
            return null;
        }

        // 获取图片的宽和高
        float width = orgBitmap.getWidth();
        float height = orgBitmap.getHeight();
        // 创建操作图片的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true);

        return bitmap;
    }


    public static Bitmap losslessScale(String path,int quality){
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
      //  bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        Log.e("哈哈","原始大小：" + baos.toByteArray().length);
        // 因为质量压缩不是可以无限缩小的，所以一张高质量的图片，再怎么压缩，
        // 最终size可能还是大于你指定的size，造成异常
        // 所以不建议循环压缩，而是指定quality，进行一次压缩就可以了
//        while (baos.toByteArray().length / 1024 > maxSize) {
//            quality -= 10;
//            baos.reset();
//            bitmap.compress(CompressFormat.JPEG, quality, baos);
//            Log.e("哈哈","过程中大小为："
//                    + baos.toByteArray().length);
//        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        Log.e("哈哈","最终大小" + baos.toByteArray().length);
        Bitmap compressedBitmap = BitmapFactory.decodeByteArray(
                baos.toByteArray(), 0, baos.toByteArray().length);
        return compressedBitmap;
    }


   public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }


}

